package utils;

import java.util.Comparator;

import myCine.alloCine.model.exchange.search.subClass.Movie;

/**
 * This class keep all comparators needed in this application
 */
public class ComparatorsStock {

	private final static int LESS = -1;
	private final static int EQUAL = 0;
	private final static int GREATHER = 1;
	
	/**
	 * Compare rate first, date in second time
	 * New movies with a good rate, will be placed in first position
	 * @param movie we compare this objet to the "movie" param
	 * @return return LESS if this movie is lether than "movie" param, EQUAL equal, 1 greater
	 */
	public final static Comparator<Movie> YOUNGEST_AND_BEST_RATED_MOVIE = new Comparator<Movie>()
	{
	    public int compare(Movie movie1, Movie movie2)
	    {
	    	int value = EQUAL;
	    	
	    	value = compareRate(movie1,movie2);
	    	if(value != EQUAL){
	    		return value;
	    	}
	    	
	    	value = compareDate(movie1,movie2);
	    	if(value != EQUAL){
	    		return value;
	    	}
	    	
	    	return EQUAL;
	    }
	    
	    /** Compare on rate */
	    private int compareRate(Movie movie1, Movie movie2){
			
			boolean movie1Rate = movie1.getStatistics() != null && movie1.getStatistics().getUserRating() != null;
			boolean movie2Rate = movie2.getStatistics() != null && movie2.getStatistics().getUserRating() != null;
			if(movie1Rate && movie2Rate){
				
				int value = movie1.getStatistics().getUserRating().compareTo(movie2.getStatistics().getUserRating());
				
				if(value == LESS){
					return GREATHER;
				} else if(value == GREATHER){
					return LESS;
				} else {
					return EQUAL;
				}
				
			} else if(movie1Rate && !movie2Rate){
				return LESS;
			} else if(!movie1Rate && movie2Rate){
				return GREATHER;
			} else {
				return EQUAL;
			}
	    }
	    
	    /** Compare on date */
	    private int compareDate(Movie movie1, Movie movie2){
	    	
			if(movie1.getProductionYear() != null && movie2.getProductionYear() != null){
				
				if(movie1.getProductionYear() > movie2.getProductionYear()){
					return LESS;
				} else if(movie1.getProductionYear() < movie2.getProductionYear()){
					return GREATHER;
				} else {
					return EQUAL;
				}
				
			} else if(movie1.getProductionYear() != null && movie2.getProductionYear() == null){
				return LESS; //second movie is too old or he is new
			} else if (movie1.getProductionYear() == null && movie2.getProductionYear() != null){
				return GREATHER; //first movie is too old or he is new
			} else {
				return EQUAL;
			}
	    }
	};
	
	/*====================================
	 *   	DEFAULT MOVIE COMPARATOR
	 *====================================*/
	
	public final static Comparator<Movie> DEFAULT_MOVIE_COMPARATOR = YOUNGEST_AND_BEST_RATED_MOVIE;
	
}
